package main

import (
	"encoding/json"
	"fmt"
	"log"
	"net/http"
	"os"
	"os/signal"
	"syscall"
)

// /Users/liyuan/IdeaProjects/notes/company/面试经验/恩士讯/tasks/main
// liyuan.cn/m2
func main() {
	port := "8081"
	if os.Getenv("SERVER_PORT") != "" {
		port = os.Getenv("SERVER_PORT")
	}
	initHandler()
	log.Println("Running api server on port: " + port)
	err := http.ListenAndServe(":"+port, nil)
	if err != nil {
		log.Printf("[Error] ListenAndServe: %v", err)
	}
	go handleSignals()
}

func initHandler() {
	http.HandleFunc("/healthz", func(writer http.ResponseWriter, request *http.Request) {
		retStr, _ := json.Marshal("NCS DBS DevOps Engineer ok")
		fmt.Fprint(writer, string(retStr))
	})
	http.Handle("/", http.FileServer(http.Dir("build")))
}

func handleSignals() {
	s := make(chan os.Signal, 1)
	signal.Notify(s, syscall.SIGILL, syscall.SIGTERM, syscall.SIGABRT)
	signalHandler(<-s)
}

func signalHandler(o os.Signal) {
	fmt.Println("\n signal: %+v", o)
	switch o {
	case syscall.SIGHUP:

	}
	fmt.Println("Finshed Server")
	os.Exit(0)
}
